// ignore_for_file: prefer_const_constructors

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:get/get.dart';
import 'package:multi_shop/models/cart_item.dart';
import 'package:multi_shop/models/order_item.dart';
import 'package:multi_shop/models/product.dart';
import 'package:multi_shop/models/sku.dart';
import 'package:multi_shop/pages/order_list.dart';
import 'package:multi_shop/services/cart_api.dart';
import 'package:multi_shop/services/product_api.dart';
import 'package:multi_shop/utils/index.dart';

/// 商品详情页面，使用 carousel_slider 插件轮播，无 Hero
class Detail extends StatefulWidget {
  final int id;
  const Detail({Key? key, required this.id}) : super(key: key);
  @override
  _DetailState createState() => _DetailState();
}

class _DetailState extends State<Detail> {
  final _cartApi = CartApi();
  int _currentIndex = 0;
  Product? _product;
  Sku? _selectedSku; // 规格选择结果（自己在弹窗里赋值）
  List<Sku> _skus = [];
  int _quantity = 0; // 购买数量（自己在弹窗里加减）
  List<String> imgs = [];
  final _api = ProductApi();
  bool _loading = true; // 加载中
  String? _error; // 错误信息
  @override
  void initState() {
    super.initState();
    _initData();
  }

  Future<void> _initData() async {
    try {
      final p = await _api.detail(widget.id);
      if (!mounted) return;
      setState(() {
        _product = p;
        _skus = p.skus;
        _selectedSku = _skus
            .where((element) => element.id == _product?.defaultSkuId)
            .first;
        imgs = p.imageUrl.split(',');
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = e.toString();
        _loading = false;
      });
    }
  }

  void _showSpecSheet({required int index}) {
    showModalBottomSheet(
      context: context,
      builder: (_) {
        // 弹窗内部的临时状态（先用当前已选的兜底）
        Sku? sel = _selectedSku;
        int qty = _quantity <= 0 ? 1 : _quantity;

        return StatefulBuilder(
          builder: (ctx, setM) {
            final primary = Theme.of(ctx).colorScheme.primary;

            return Container(
              padding: const EdgeInsets.all(16),
              height: 320,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '选择规格',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 12),

                  // 规格选择
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children: _skus.map((spec) {
                      final bool isSel =
                          (sel?.id?.toString() ?? '') ==
                              (spec.id?.toString() ?? '')
                          // 如果没有 id，就用 skuCode 比较
                          ||
                          (sel == null && false);
                      return ChoiceChip(
                        label: Text(spec.skuCode),
                        selected: isSel,
                        onSelected: (_) => setM(() => sel = spec),
                        // —— 选中样式 —— //
                        selectedColor: primary.withOpacity(0.12),
                        backgroundColor: Colors.grey.withOpacity(0.06),
                        labelStyle: TextStyle(
                          color: isSel ? primary : null,
                          fontWeight: isSel
                              ? FontWeight.w600
                              : FontWeight.normal,
                        ),
                        shape: StadiumBorder(
                          side: BorderSide(
                            color: isSel ? primary : Colors.grey.shade300,
                          ),
                        ),
                      );
                    }).toList(),
                  ),

                  const SizedBox(height: 16),

                  // 数量
                  Row(
                    children: [
                      const Text('数量：', style: TextStyle(fontSize: 16)),
                      IconButton(
                        icon: const Icon(Icons.remove_circle_outline),
                        onPressed: () => setM(() {
                          if (qty > 1) qty--;
                        }),
                      ),
                      Text('$qty', style: const TextStyle(fontSize: 16)),
                      IconButton(
                        icon: const Icon(Icons.add_circle_outline),
                        onPressed: () => setM(() => qty++),
                      ),
                      const Spacer(),
                      // 价格展示（选中规格价）
                      if (sel != null)
                        Text(
                          '¥${sel!.price.toStringAsFixed(2)}',
                          style: const TextStyle(
                            fontSize: 18,
                            color: Colors.redAccent,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                    ],
                  ),

                  const Spacer(),

                  // 确定按钮
                  SizedBox(
                    width: double.infinity,
                    height: 48,
                    child: ElevatedButton(
                      onPressed: () async {
                        if (sel == null) {
                          toastCenter('请选择规格');
                          return;
                        }

                        // 先把弹窗内的选择回写到页面 state
                        setState(() {
                          _selectedSku = sel;
                          _quantity = qty;
                        });

                        Navigator.pop(context);
                        if (index == 0) {
                          // 加入购物车
                          await _cartApi.create(_product!.id, sel!.id, qty);
                          toastCenter('添加成功');
                          Get.toNamed('/cart');
                        } else {
                          // 立即购买 -> 组装 OrderItem 并跳转
                          final item = OrderItem(
                            skuId: sel!.id,
                            goodsId: _product!.id,
                            name: _product!.name,
                            imageUrl: (imgs.isNotEmpty
                                ? imgs.first
                                : _product!.imageUrl),
                            price: sel!.price,
                            quantity: qty,
                            merchantId: _product!.merchantId,
                          );
                          Get.toNamed('/order', arguments: [item]);
                        }
                      },
                      child: const Text('确定'),
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }
    if (_error != null) {
      return Scaffold(
        appBar: AppBar(title: const Text('商品详情')),
        body: Center(
          child: TextButton(
            onPressed: _initData,
            child: Text('加载失败，点击重试\n$_error'),
          ),
        ),
      );
    }
    return Scaffold(
      appBar: AppBar(title: Text("商品详情"), elevation: 0),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CarouselSlider.builder(
              itemCount: imgs.length,
              itemBuilder: (context, index, realIdx) {
                final url = imgs[index];
                return Image.network(
                  url,
                  width: double.infinity,
                  height: 300,
                  fit: BoxFit.cover,
                  errorBuilder: (_, __, ___) => Center(
                    child: Icon(
                      Icons.broken_image,
                      size: 80,
                      color: Colors.grey,
                    ),
                  ),
                );
              },
              options: CarouselOptions(
                height: 300,
                viewportFraction: 1.0,
                enableInfiniteScroll: false,
                initialPage: 0,
                onPageChanged: (idx, reason) {
                  setState(() {
                    _currentIndex = idx;
                  });
                },
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: imgs.asMap().entries.map((entry) {
                int idx = entry.key;
                return Container(
                  width: 8,
                  height: 8,
                  margin: EdgeInsets.symmetric(horizontal: 4, vertical: 8),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: _currentIndex == idx ? Colors.black : Colors.black26,
                  ),
                );
              }).toList(),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _product!.name,
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 8),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '¥${_selectedSku?.price ?? "0.00"}',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          color: Colors.redAccent,
                        ),
                      ),
                      //销量
                      Text(
                        "已售 ${_product?.sales}",
                        style: const TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w400,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 16),
                  // ===== 商家信息模块 =====
                  InkWell(
                    onTap: () {
                      Get.toNamed('/merchant_home', arguments: 1);
                    },
                    child: Container(
                      color: const Color.fromARGB(255, 248, 248, 248),
                      padding: const EdgeInsets.all(12),
                      child: Row(
                        children: [
                          CircleAvatar(
                            radius: 28,
                            backgroundImage: NetworkImage(
                              "https://img.alicdn.com/imgextra/i2/2067227577/O1CN01xpAVpL25qK3WbBy6T_!!2067227577.jpg_760x760q30.jpg_.webp",
                            ),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "StrongDream梦之强旗舰店",
                                  style: const TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  "梦之强旗舰店",
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.grey,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const Icon(Icons.chevron_right, color: Colors.grey),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 16),
                  Text(
                    '商品描述',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                  ),
                  SizedBox(height: 8),
                  Text(
                    _product!.name,
                    style: TextStyle(fontSize: 14, height: 1.5),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: Container(
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        color: Colors.white,
        child: Row(
          children: [
            IconButton(
              icon: Icon(Icons.chat_bubble_outline),
              onPressed: () {
                // TODO: 联系客服
                Get.toNamed('/msg');
              },
            ),
            Expanded(
              child: OutlinedButton(
                onPressed: () => _showSpecSheet(index: 0),
                child: Text('加入购物车', maxLines: 1, softWrap: false),
              ),
            ),
            SizedBox(width: 8),
            Expanded(
              child: ElevatedButton(
                onPressed: () => _showSpecSheet(index: 1),
                child: Text('立即购买', maxLines: 1, softWrap: false),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
